package com.means.polymerize.assembly.filter;

import lombok.*;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Xss 过滤器
 *
 * @author xuhaifeng
 * @date 2021.05.05
 */
@AllArgsConstructor
public class XssFilter extends OncePerRequestFilter {
    /**
     * 属性
     */
    private final XssProperties properties;
    /**
     * 路径匹配器
     */
    private final PathMatcher pathMatcher;

    @Override
    @SneakyThrows(value = {IOException.class, ServletException.class})
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        filterChain.doFilter(new XssRequestWrapper(request), response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        /* 如果关闭，则不过滤 */
        if (!properties.isEnable()) {
            return true;
        }
        /* 如果匹配到无需过滤，则不过滤 */
        return properties.getExcludeUrls().stream().anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, request.getRequestURI()));
    }

    /**
     * Xss属性
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class XssProperties {
        /**
         * 是否开启，默认为 true
         */
        private boolean enable;
        /**
         * 需要排除的 URL，默认为空
         */
        private List<String> excludeUrls;
    }

}
